package com.gmu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gmu.domain.LoginAdminDetails;
import com.gmu.domain.LoginUserDetails;
import com.gmu.domain.ResResult;
import com.gmu.mapper.TblDoctorMapper;
import com.gmu.mapper.TblStudentMapper;
import com.gmu.mapper.TblTeacherMapper;
import com.gmu.mapper.TblUserMapper;
import com.gmu.pojo.*;
import com.gmu.pojo.vo.MsgResult;
import com.gmu.pojo.vo.RegisterVo;
import com.gmu.service.LoginService;
import com.gmu.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.ehcache.shadow.org.terracotta.offheapstore.storage.HalfStorageEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author 木鱼~
 * @version 1.0
 */
@Api(tags= "登录/注销API")
@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private TblUserMapper tblUserMapper;

    @Autowired
    private TblStudentMapper tblStudentMapper;

    @Autowired
    private TblDoctorMapper tblDoctorMapper;

    @Autowired
    private TblTeacherMapper tblTeacherMapper;

    /**
     * 用户身份证号登录
     * @param idNumber 身份证号
     * @param password 密码
     * @return
     */
    @ApiOperation(value = "用户身份证号登录")
    @PostMapping("/login")
    public ResResult<?> login(String idNumber, String password){
        return loginService.login(idNumber,password);
    }

    /**
     * 手机短信登录
     */
    @ApiOperation(value = "手机短信登录")
    @PostMapping("/loginByPhone")
    public ResResult<?> loginByPhone(String phone,String code){
        return loginService.loginByPhone(phone,code);
    }

    /**
     * 返回用户的登录信息
     */
    @ApiOperation(value = "返回登录用户的信息")
    @GetMapping("/userInfo")
    public ResResult<HashMap<String, Object>> getUserInfo(){
        LoginUserDetails loginUserDetails = (LoginUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (Objects.isNull(loginUserDetails)){
            return new ResResult<>(401,"未登录，请先登录");
        }
        HashMap<String, Object> map = new HashMap<>();
        TblUser tblUser = loginUserDetails.getTblUser();
        map.put("roleId",tblUser.getRoleId());
        if (tblUser.getRoleId() == 1){ //1--学生
            LambdaQueryWrapper<TblStudent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TblStudent::getUserId,tblUser.getUserId());
            TblStudent tblStudent = tblStudentMapper.selectOne(wrapper);
            map.put("studentInfo",tblStudent);
        }else if (tblUser.getRoleId() == 2){ //2--老师
            LambdaQueryWrapper<TblTeacher> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TblTeacher::getUserId,tblUser.getUserId());
            TblTeacher tblTeacher = tblTeacherMapper.selectOne(wrapper);
            map.put("teacherInfo",tblTeacher);
        }else if (tblUser.getRoleId() == 3){ //3--医护人员
            LambdaQueryWrapper<TblDoctor> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TblDoctor::getUserId,tblUser.getUserId());
            TblDoctor tblDoctor = tblDoctorMapper.selectOne(wrapper);
            map.put("doctorInfo",tblDoctor);
        }else {
            return new ResResult<>(404,"未找到该角色");
        }
        return new ResResult<>(200,map);
    }

    /**
     * 管理员账号登录
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @ApiOperation(value = "管理员账号登录")
    @PostMapping("/loginAdmin")
    public ResResult<?> loginAdmin( String username, String password, String code){
        return loginService.loginAdmin(username,password,code);
    }

    /**
     * 管理员修改密码
     */
    @ApiOperation(value = "管理员修改密码")
    @PutMapping("/adminUpdatePassword/{oldPassword}/{newPassword}")
    public ResResult<?> adminUpdatePassword(@PathVariable String oldPassword,@PathVariable String newPassword){
        return loginService.adminUpdatePassword(oldPassword,newPassword);
    }

    /**
     * 修改用户信息
     */
    @ApiOperation(value = "修改用户信息")
    @PostMapping("/adminUpdateInfo")
    public ResResult<?> adminUpdateInfo(@RequestBody TblAdmin tblAdmin){
        return loginService.adminUpdateInfo(tblAdmin);
    }

    /**
     * 返回管理员的登录信息
     */
    @ApiOperation(value = "返回管理员的登录信息")
    @GetMapping("/adminInfo")
    public ResResult<?> adminInfo(){
        LoginAdminDetails loginAdminDetails
                = (LoginAdminDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (Objects.isNull(loginAdminDetails)){
            return new ResResult<>(500,"请重新登录");
        }
        TblAdmin tblAdmin = loginAdminDetails.getTblAdmin();
        tblAdmin.setPassword(null);
        return new ResResult<>(200,tblAdmin);
    }

    /**
     * 用户退出登录
     */
    @ApiOperation(value = "用户退出登录")
    @PostMapping("/user/logout")
    public ResResult<?> userLogout(){
        return loginService.logout();
    }

    /**
     * 管理员退出登录
     */
    @ApiOperation(value = "管理员退出登录")
    @PostMapping("/admin/logout")
    public ResResult<?> AdminLogout(){
        return loginService.AdminLogout();
    }

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    //注册用户信息
    @ApiOperation("注册")
    @PostMapping("/register")
    public ResResult register(@RequestBody RegisterVo registerVo){
        return loginService.register(registerVo);
    }

    //发送短信
    @ApiOperation("发送验证码")
    @PostMapping("/send/{phone}")
    public ResResult send(@PathVariable String phone){
        //1 从redis获取验证码，如果有直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return new ResResult(200,"获取成功");
        }

        //2 如果获取失败，则进行乐讯通短信发送
        //生成随机数
        code = RandomUtil.getFourBitRandom();

        //调用service发送短信的方法
        MsgResult msgResult = loginService.sendMsgPost(phone,code);
        if("success".equals(msgResult.getReturnstatus()) && msgResult.getCode()==0){
            //发送成功，把发送成功验证码放到redis里面
            //设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return new ResResult(200,"发送成功");
        }else {
            return new ResResult(201,"发送失败",msgResult.getRemark());
        }
    }


}
